<?php

declare(strict_types=1);

namespace app\certificate\controller\admin\v1;


use think\facade\Db;
use think\Request;

class Area
{
    /**
     * @Description: 列表
     * @param {Request} $request
     */
    public function getList(Request $request)
    {
        $data  = $request->data;
        $limit =  $data['limit'];
        $page =  $data['page'];
        $where = [
            ['projectCode', '=', $request->authWhere['projectCode']],
            ['isDelete', '=', $data['status'] ?? 0],
        ];
        if (!empty($data['name'])) array_push($where, ['name', 'like', "%" . $data['name'] . "%"]);

        //判断身份
        if (isset($request->authWhere['corpCode'])) {
            array_push($where, ['corpCode', '=', $request->authWhere['corpCode']]);
        } elseif (!empty($data['corpCode'])) {
            array_push($where, ['corpCode', '=', $data['corpCode']]);
        }


        $list =  DB::table('certificate_area')
            ->where($where)
            ->page((int)$page, (int)$limit)
            ->field(['inDate', 'corpCode', 'name', 'uuid'])
            ->order(['id desc'])
            ->select()->toArray();

        $count =  DB::table('certificate_area')
            ->where($where)
            ->count('id');

        $data = [
            'list' => $list,
            'count' => $count,
        ];
        return result(SUCCESS, $data, '');
    }
    /**
     * @Description: 添加
     * @param {Request} $requestdestroyde
     */
    public function create(Request $request)
    {
        $data = $request->data;
        $data['uuid']  = createUuid();
        $data['projectCode']  = $request->prjCode;
        $data['corpCode']  = $request->corpCode;
        DB::startTrans();
        try {
            //添加区域
            DB::table('certificate_area')->insert($data);
            DB::commit();
            $data['inDate'] = date('Y-m-d', $_SERVER['REQUEST_TIME']);
            return result(SUCCESS, $data, '添加成功');
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
        }
        return result(FAIL, '', '添加失败,请重试');
    }
    /**
     * @Description: 修改
     */
    public function update(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];
        $cehck = DB::table('certificate_area')->where([
            ['uuid', '<>', $uuid],
            ['name', '=', $data['name']],
            ['isDelete', '=', 0],
            ['projectCode', '=', $request->prjCode],
        ])->value('id');
        if ($cehck) return result(FAIL, '', '名称已存在,无法修改!');

        $oldName = DB::table('certificate_area')->where([
            ['uuid', '=', $uuid],
            ['isDelete', '=', 0]
        ])->value('name');
        if (!$oldName) return result(FAIL, '', '区域已被删除无法修改!');

        $updateData = [
            'name' => $data['name'],
        ];
        $return = [];

        DB::table('certificate_area')->where('uuid', $uuid)->update($updateData);
        return result(SUCCESS, $return, '保存成功');
    }

    public function destroy(Request $request)
    {
        $data = $request->data;
        DB::table('certificate_area')->where('uuid', $data['uuid'])->update([
            'isDelete' => 1,
        ]);
        return result(SUCCESS, '', '删除成功');
    }

    /**
     * @Description: 获取数据
     * @param {Request} $request
     */
    public function getDetail(Request $request)
    {
        $data = $request->data;
        $uuid = $data['uuid'];

        $data = DB::table('certificate_area')->where('uuid', $uuid)->field(['name', 'inDate', 'uuid', 'corpCode'])->find();

        return result(SUCCESS, $data, '');
    }

    /**
     * @Description: 获取区域人员列表
     * @param {Request} $request
     */
    public function getWorkerList(Request $request)
    {
        $data = $request->data;
        $where = [
            ['projectCode','=',$request->prjCode],
            ['isDelete','=',0],
            ['entryTime','<>','0000-00-00 00:00:00'],
            ['exitTime','=','0000-00-00 00:00:00'],
        ];

        $list = DB::table('certification_projectWorker')
        ->where($where)
        ->where($request->authWhere)
        ->field(['teamName','workerName','teamSysNo','wxappUserUuid','corpName','corpCode'])
        ->group(['wxappUserUuid','corpCode'])
        ->select()->toArray();

        foreach($list as $key => $value){
            if(empty($value['workerName'])){
                $list[$key]['workerName'] = DB::table('platform_wxappUser')->where('wxappUserUuid',$value['wxappUserUuid'])->value('nickName');
            }
        }
        
        $list = $this->centerProcess($list);
        
        $checked = DB::table('certificate_areaWorker')
            ->where(['areaUuid' => $data['uuid'], 'isDelete' => 0])
            ->column('wxappUserUuid');

        $data = compact('list', 'checked');

        return result(SUCCESS, $data, '');
    }

    //人员分类信息     
    private function centerProcess($data){
        if(!$data) return $data;
        $arr = [];
        foreach($data as $key=>$value){
            if(empty($value['workerName'])){
                $wxappUserData = DB::table('platform_wxappUser')->where('wxappUserUuid',$value['value'])->field(['nickName'])->findOrEmpty();

                if(empty($wxappUserData)) continue;
                $value['workerName'] = $wxappUserData['nickName'];
                $value['hasWorkerInfo'] = 0;
            }
            $data = [
                'value'=>$value['wxappUserUuid'],
                'name'=>$value['workerName'],
                'corpCode'=>$value['corpCode'],
            ];
            $arr[$value['corpCode']]['name']=$value['corpName'];
            $arr[$value['corpCode']]['children'][$value['teamSysNo']]['name'] = $value['teamName'];
            $arr[$value['corpCode']]['children'][$value['teamSysNo']]['children'][] = $data;
        }
        sort($arr);
        foreach($arr as $key=>$value){
            if(isset($value['children'])){
                sort($value['children']);
                $arr[$key]['children'] = $value['children'];
            }
        }
        return $arr;
    }
    /**
     * @Description: 获取所属许可证类型列表
     * @param {Request} $request
     */
    public function getTypeList(Request $request)
    {
        $data = $request->data;

        $where = [
            ['projectCode', '=', $request->prjCode],
            ['isDelete', '=', 0],
        ];
        if (!empty($request->authWhere['corpCode'])) array_push($where, ['corpCode', '=', $request->corpCode]);

        $riskTypelist = DB::table('certificate_riskType')
            ->where(array_merge($where))
            ->field(['name', 'uuid'])
            ->select()->toArray();
        $riskTypechecked = DB::table('certificate_areaType')
            ->where(['areaUuid' => $data['uuid'], 'isDelete' => 0, 'type' => 1])
            ->column('typeUuid');
       
        $checkListTypelist = DB::table('certificate_heavyMachineCheckType')
            ->where(array_merge($where))
            ->field(['name', 'uuid'])
            ->select()->toArray();
        $checkListTypechecked = DB::table('certificate_areaType')
            ->where(['areaUuid' => $data['uuid'], 'isDelete' => 0, 'type' => 2])
            ->column('typeUuid');

        $data = compact('riskTypelist', 'riskTypechecked','checkListTypelist','checkListTypechecked');
        return result(SUCCESS, $data, '');
    }

    /**
     * @Description: 修改所属人员
     * @param {Request} $request
     */
    public function changeWorker(Request $request)
    {
        $data = $request->data;
        $areaUuid = $data['uuid'];

        $globalData = dataMerge($request->uuid, [
            'areaUuid' => $areaUuid,
        ]);

        $oldData =  DB::table('certificate_areaWorker')
            ->where(['areaUuid' => $data['uuid'], 'isDelete' => 0])
            ->column('wxappUserUuid');
        $newData =  array_column($data['value'], 'wxappUserUuid');
        $create = array_diff($newData, $oldData);
        $delete = array_diff($oldData, $newData);

        DB::startTrans();
        try {
            if ($create) {
                $create = array_unique($create);
                foreach ($create as $key => $value) {
                    $insertData[] = array_merge(['wxappUserUuid' => $value, 'uuid' => createUuid()], $globalData);
                }
                DB::table('certificate_areaWorker')->insertAll($insertData);
            }
            if ($delete) {
                DB::table('certificate_areaWorker')
                    ->where([
                        'wxappUserUuid' => $delete,
                        'areaUuid' => $areaUuid,
                    ])
                    ->update(['isDelete' => 1]);
            }
            DB::commit();
            return result(SUCCESS, '', '更新成功');
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            return result(FAIL, '', '更新失败');
        }
    }

    /**
     * @Description: 修改许可证类型
     * @param {Request} $request
     */
    public function changeType(Request $request)
    {
        $data = $request->data;
        $areaUuid = $data['uuid'];

        $globalData = dataMerge($request->uuid, [
            'areaUuid' => $areaUuid
        ]);
        $riskTypeData = $data['riskTypeValue'];
        $checkListTypeData = $data['checkListTypeValue'];
        DB::startTrans();
        try {
            DB::table('certificate_areaType')
            ->where([
                'areaUuid' => $areaUuid,
            ])
            ->delete();

            foreach ($riskTypeData as $key => $value) {
                $insertData[] = array_merge(['typeUuid' => $value, 'uuid' => createUuid(),'type' => 1], $globalData);
            }
            foreach ($checkListTypeData as $key => $value) {
                $insertData[] = array_merge(['typeUuid' => $value, 'uuid' => createUuid(),'type' => 2], $globalData);
            }
            DB::table('certificate_areaType')->insertAll($insertData);
            DB::commit();
            return result(SUCCESS, '', '更新成功');
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollback();
            return result(FAIL, '', '更新失败');
        }
    }
}
